import io from "../../libs/weapp.socket.io.js";
// import io from 'weapp.socket.io';

class PeonyClient {
  isConnected = false;
  socket = null;
  socketId = null;
  lockReConnect = false;
  timer = null;
  errorCount = 0;
  tryCount = 0;
  socketUrl = "";
  userId = "";
  params = {};
  MessageListener = []; // 需要多个地方处理的消息监听
  MessageGroupListener = []; // 需要多个地方处理的消息监听
  SysMessageCallBack = (data: any) => {};
  GroupNotifySuccess = (data: any) => {};
  ConnectSuccess = (data: any) => {};
  GroupNotifyError = (data: any) => {};
  JoinGroupToAdmin = []; // 需要多个地方处理的消息监听
  InvitedGroupGroupToUser = []; // 需要多个地方处理的消息监听

  constructor() {}
  jsonToParamsStr = (json_params) => {
    var params = Object.keys(json_params)
      .map(function (key) {
        // body...
        return (
          encodeURIComponent(key) + "=" + encodeURIComponent(json_params[key])
        );
      })
      .join("&");
    return params;
  };

  init(socketUrl, params) {
    const _this = this;
    _this.socketUrl = socketUrl;
    _this.params = params;
    _this.userId = params.userId;
    _this.connectSocket();
  }
  connectSocket() {
    const _this = this;
    console.log(_this.socketUrl);
    _this.socket = io(
      _this.socketUrl + "?" + _this.jsonToParamsStr(_this.params),
      {
        transports: ["websocket"],
        // reconnectionAttempts : 2,     // 重连尝试次数
        reconnectionDelay: 3000, // 失败重连的时间间隔(ms)
        // timeout : 20000,              // 连接超时时间(ms)
        forceNew: false, //设置每次使用新的连接客户端
        // reconnection : true,         //设置断开重连
      }
    );
    console.log("connectSocket");

    _this.initSocketEvent();
  }

  initSocketEvent() {
    // socketIO会自动重连 注释掉重连逻辑
    const _this = this;
    _this.socket.on("connected", function (data: any) {
      _this.isConnected = true;
      console.log("连接成功", data.id);
      _this.socketId = data.id;
      _this.errorCount = 0;
      data.type = "connected";
      _this.ConnectSuccess && _this.ConnectSuccess(data);
    });
    _this.socket.on("disconnect", function () {
      if (_this.isConnected) {
        console.log("连接断开");
        _this.reconnectSocket();
      }
    });
    _this.socket.on("error", function (data) {
      _this.reconnectSocket();
      console.log("链接错误");
    });

    _this.socket.on("message", function (data: any) {
      if (data.type == "message") {
        //普通消息
        _this.MessageListener.forEach((callback) => {
          callback(data);
        });
      } else if (data.type == "systemMessage") {
        //系统消息
        _this.SysMessageCallBack(data);
      } else {
        //服务器拒绝了
      }
      console.log("onSocketMessage:", data);
    });

    _this.socket.on("messageGroup", function (data) {
      if (data.type == "systemMessage") {
        //系统消息
        _this.SysMessageCallBack(data);
      } else {
        //直接抛给业务层
        _this.MessageGroupListener.forEach((callback) => {
          callback(data);
        });
      }
      console.log(data.type, data.userId + "：" + data.message);
    });

    _this.socket.on("joinAgreeGroup", function (data) {
      if (data.toAdmin == "invited") {
        if (data.type == "agree") {
          console.log("joinAgreeGroup:", data.userId + "同意进群了");
          // 通知订阅
          _this.GroupNotifySuccess && _this.GroupNotifySuccess(data);
        } else {
          console.log("joinAgreeGroup:", data.userId + "不同意进群");
          data.message = data.userId + "不同意进群";

          _this.GroupNotifyError && _this.GroupNotifyError(data);
        }
      } else {
        if (data.type == "agree") {
          console.log("joinAgreeGroup:", data.userId + "同意进群了");
          _this.GroupNotifySuccess && _this.GroupNotifySuccess(data);
        } else {
          console.log("joinAgreeGroup:", data.roomId + " 的群主拒绝了您进群");
          data.message = data.roomId + " 的群主拒绝了您进群";
          _this.GroupNotifyError && _this.GroupNotifyError(data);
        }
      }
    });
    _this.socket.on("joinGroup", function (data) {
      if (data.roomId) {
        data.type = "joinGroup";
        _this.GroupNotifySuccess && _this.GroupNotifySuccess(data);

        //需要回显到界面上
        if (data.message) {
          console.log(data.userId + "," + data.message);
        } else {
          console.log(data.userId + "加入房间");
        }
      } else {
        console.log(data.message);
        this.GroupNotifyError(data);
      }
    });
    _this.socket.on("exitGroup", function (data) {
      if (data.roomId) {
        data.value = data.type;
        data.type = "exitGroup";
        _this.GroupNotifySuccess && _this.GroupNotifySuccess(data);

        if (data.ownerId == data.userId) {
          console.log("离开了", data.ownerId + "," + data.message);
        } else {
          console.log("管理", data.ownerId + "," + data.message);
        }
      } else {
        this.GroupNotifyError(data);
      }
    });
    _this.socket.on("close", function (data) {
      if (data.roomId) {
        data.type = "close";
        _this.GroupNotifySuccess && _this.GroupNotifySuccess(data);

        console.log("掉线了", data.userId);
      } else {
        this.GroupNotifyError(data);
      }
    });
    _this.socket.on("joinInvitedGroup", function (data) {
      // 群管理的消息
      if (data.type == "invited") {
        _this.InvitedGroupGroupToUser.forEach((callback) => {
          callback(data);
        });
      } else {
        _this.JoinGroupToAdmin.forEach((callback) => {
          callback(data);
        });
      }
    });
  }

  reconnectSocket() {
    // const _this = this
    // if (_this.lockReConnect) {
    //   return
    // }
    // _this.lockReConnect = true
    // clearTimeout(_this.timer)
    // if (_this.errorCount < 10) {
    //   _this.timer = setTimeout(() => {
    //     _this.connectSocket()
    //     _this.lockReConnect = false
    //   }, 5000)
    //   _this.errorCount = _this.errorCount + 1
    // } else {
    //   _this.closeSocket()
    // }
  }

  sendSocketMessage(message, callback = () => {}) {
    const _this = this;
    _this.socket.emit("message", { ...message, socketId: _this.socketId });
  }

  emit(type, message, callback = () => {}) {
    const _this = this;
    //这里可以加密消息
    if (_this.socket == null && this.tryCount < 3) {
      console.log("socket 失联 ...", this.tryCount);
      setTimeout(() => {
        this.emit(type, message);
        this.tryCount++;
      }, 1000);
    } else {
      this.tryCount = 0;
      _this.socket.emit(type, { ...message, socketId: _this.socketId });
    }
  }

  //封装一下
  onSocketMessage(callback = (msg: any) => {}) {
    this.MessageListener.push(callback);
  }
  onSocketSysMessage(callback = (msg: any) => {}) {
    this.SysMessageCallBack = callback;
  }
  onSocketMessageGroup(callback = (msg: any) => {}) {
    this.MessageGroupListener.push(callback);
  }

  // 进群通知
  onSocketGroupNotify(
    sucessFun = (msg: any) => {},
    errorFun = (msg: any) => {}
  ) {
    this.GroupNotifySuccess = sucessFun;
    this.GroupNotifyError = errorFun;
  }
  onConnectSuccess(
    sucessFun = (msg: any) => {},
  ) {
    this.ConnectSuccess = sucessFun;
  }

  // 进群弹框 群主弹框，用户被邀请弹框 分开两个
  onSocketJoinGroupToAdmin(sucessFun = (msg: any) => {}) {
    this.JoinGroupToAdmin.push(sucessFun);
  }
  onSocketInvitedGroupGroupToUser(sucessFun = (msg: any) => {}) {
    this.InvitedGroupGroupToUser.push(sucessFun);
  }

  // 单个移除
  removeMessageListener(fun) {
    this.MessageListener.map((item, index) => {
      if (item === fun) {
        this.MessageListener.splice(index, 1);
      }
    });

    this.MessageGroupListener.map((item, index) => {
      if (item === fun) {
        this.MessageGroupListener.splice(index, 1);
      }
    });

    this.JoinGroupToAdmin.map((item, index) => {
      if (item === fun) {
        this.JoinGroupToAdmin.splice(index, 1);
      }
    });

    this.InvitedGroupGroupToUser.map((item, index) => {
      if (item === fun) {
        this.InvitedGroupGroupToUser.splice(index, 1);
      }
    });
  }
  // 移除最后一个
  removeMessageListenerAll() {
    this.MessageListener.splice(this.MessageListener.length - 1, 1);
    this.MessageGroupListener.splice(this.MessageGroupListener.length - 1, 1);

    this.JoinGroupToAdmin.splice(this.JoinGroupToAdmin.length - 1, 1);
    this.InvitedGroupGroupToUser.splice(
      this.InvitedGroupGroupToUser.length - 1,
      1
    );
  }
  closeSocket() {
    this.socket && this.socket.close();
  }
  disconnect() {
    if (this.isConnected) {
      this.isConnected = false;
      console.log("手动连接断开");
      this.closeSocket();
    }
  }
}

export default new PeonyClient();
